package org.example.managementsystem.service;

import org.example.managementsystem.model.Person;
import org.example.managementsystem.model.User;
import org.example.managementsystem.repository.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserService {
    private final UserDao userDao;
    private final PersonService personService;
    private final BCryptPasswordEncoder passwordEncoder;

    @Autowired
    public UserService(UserDao userDao, PersonService personService) {
        this.userDao = userDao;
        this.personService = personService;
        this.passwordEncoder = new BCryptPasswordEncoder();
    }

    /**
     * 用户登录
     * @param username 用户名（工号或手机号）
     * @param password 密码
     * @param role 角色
     * @return 登录成功返回用户信息，失败返回null
     */
    public User login(String username, String password, String role) {
        User user = null;

        // 尝试以工号查询
        user = userDao.getUserByJobNumber(username);

        // 如果未找到，尝试以手机号查询
        if (user == null) {
            user = userDao.getUserByPhone(username);
        }

        // 验证用户名、密码和角色，只有全部匹配才允许登录
        if (user == null || !password.equals(user.getPassword()) || !user.getRole().equals(role)) {
            return null;
        }

        // 生成令牌
        String token = generateToken();
        user.setToken(token);
        // 不返回密码
        user.setPassword(null);

        // 查询人员表获取姓名等信息填充进User类
        Person person = personService.getPersonByJobNumber(user.getJobNumber());
        user.setName(person.getName());
        user.setDepartment(person.getDepartment());

        return user;
    }

    /**
     * 检查用户角色是否匹配
     */
    private boolean matchRole(String userRole, String requestRole) {
        // 修改为直接比对角色字符串
        return userRole != null && userRole.equals(requestRole);
    }

    /**
     * 生成令牌
     */
    private String generateToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 根据工号获取用户
     */
    public User getUserByJobNumber(String jobNumber) {
        return userDao.getUserByJobNumber(jobNumber);
    }

    /**
     * 更新用户信息
     */
    public int updateUser(User user) {
        return userDao.updateUser(user);
    }
}
